import optionService from '@/apis/option'
import carService from '@/apis/car'
import serviceService from '@/apis/service'
import orderService from '@/apis/order'
import userService from '@/apis/user'
import { formattedGMTDate } from '@/utils/util'

// components/order-detail/order-detail.js
Component({

  /**
   * 组件的属性列表
   */
  properties: {
    order_id: {
      type: Number,
      value: 0,
      //获得orderId的新值和旧值
      observer: async function(newVal, oldVal) { // 新增观察器监听order变化
        //如果新值和旧值不同
        if (newVal !== oldVal) {
          this.onLoad() // 当order变化时重新执行初始化
        }
      }
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    showModal: false,
    memoplus: '',

    order:{},
    referrerList: [],
    selectedReferrer: '',
    selectedReferrerId: '',

    CustomerTypeList: [],
    selectedCustomerType: '',
    selectedCustomerTypeId: '',

    name: '',
    phone: '',
    isPhoneValid: true,
    CustomerSrcList: [],
    selectedCustomerSrc: '',
    selectedCustomerSrcId: '',
    idTypeList: [],
    selectedIdType: '',
    selectedIdTypeId: '',
    idNumber: '',
    address: '',
    vin: '',
    purchaseTypeList: [],
    selectedPurchaseType: '',
    selectedPurchaseTypeId: '',
    carPrice: '',
    seatsList: [],
    selectedSeats: '',
    selectedSeatsId: '',
    engineNumber: '',
    carColor: '',
    purchaseDate: "",
    currentDate: new Date().toISOString().split('T')[0],
    carList: [],
    selectedCarId: '',
    multiIndex: [0, 0, 0],  // 当前选中的三级索引
    brands: [],           // 省份列表
    models: [],              // 城市列表
    styles: [],            // 区县列表
    carsMap: new Map(), // 省份Map
    serviceList: [],
    selectedServices: [],
    selectedServicesId: [],

    showCustomPicker: false,
    serviceMap: {},
    serviceList: [],
    categoryNames: [],
    totalPrice: 0,


    has_modification: 0,
    invoiceImagePath: "", // 预览图片路径
    modificationImagePath: "", // 预览图片路径

    store_id: 0,
    memo: '',

    paymentList: [],
    selectedPayment: '',
    selectedPaymentId: '',
  },

  

  /**
   * 组件的方法列表
   */
  methods: {
    handleGiftChange(e) {
      const {csa_id} = e.detail;
      console.log(csa_id)
      //查找selectedServices中查找id为csa_id的对象
      const service = this.data.selectedServices.find(service => service.csa_id === csa_id);
      if (service) {
        //修改service的is_gift属性在0和1之间来回切换
        service.is_gift = service.is_gift === 0 ? 1 : 0;
        this.setData({
          selectedServices: this.data.selectedServices,
        });
      }
      //计算总价
      this.calculateTotalPrice();
    },
    //定义函数，计算selectedServices中除了is_gift为true的对象的price之和
    calculateTotalPrice() {
      const totalPrice = this.data.selectedServices.reduce((total, service) => {
        if (!service.is_gift) {
          return total + service.price;
        }
        return total;
      }, 0);
      this.setData({
        totalPrice,
      });
    },
    showModal(e) {
      this.setData({ showModal: true });
    },
  
    cancelInput() {
      this.setData({ 
        showModal: false,
        memoplus: '',
      });
    },
  
    confirmInput() {
      const memoplus= this.data.memoplus.trim();
      if (memoplus) {
        // 执行后续逻辑
        this.failOrder(memoplus);
      }else{
        wx.showToast({
          title: '请输入战败备注',
          icon: 'none' 
        })
      }
    },

    async onLoad(options) {
      //显示加载动画并禁止页面操作
      wx.showLoading({
        title: '加载中...',
        mask: true 
      })
      const id=this.properties.order_id;
      if(!id){
        wx.hideLoading()
        return; 
      }
      //从orderService中获得order对象
      var ress = await Promise.all([
        orderService.getDetail(id),
        userService.get_referrer(),
        optionService.get_category("客户类型"),
        optionService.get_category("客户来源"),
        optionService.get_category("证件类型"),
        optionService.get_category("购车类型"),
        optionService.get_category("座位数"),
        optionService.get_category("支付方式"),
        carService.list()
      ])
      const app=getApp()
      //验证order对象为空对象
      const order = ress[0].data.data
      //只提取id、order_number、order_status组成新对象，替换app.globalData中的order
      app.globalData.order = {
        id: order.id,
        order_number: order.order_number,
        order_status: order.order_status, 
      }
      console.log(order)
      this.setData({
        order,
        referrerList: ress[1].data.data,
        selectedReferrer: order.rname||app.globalData.userInfo.username,
        selectedReferrerId: order.rid||app.globalData.userInfo.id,
        CustomerTypeList: ress[2].data.data,
        selectedCustomerType: order.ctname||ress[2].data.data[0].option,
        selectedCustomerTypeId: order.ctid||ress[2].data.data[0].id,
        name: order.cname||'',
        phone: order.cphone||'',
        CustomerSrcList: ress[3].data.data,
        selectedCustomerSrc: order.csname||ress[3].data.data[0].option,
        selectedCustomerSrcId: order.csid||ress[3].data.data[0].id,
        idTypeList: ress[4].data.data,
        selectedIdType: order.itname||ress[4].data.data[0].option,
        selectedIdTypeId: order.itid||ress[4].data.data[0].id,
        idNumber: order.id_number||'',
        address: order.address||'',
        vin: order.vin||'',
        purchaseTypeList: ress[5].data.data,
        selectedPurchaseType: order.ptname||ress[5].data.data[0].option,
        selectedPurchaseTypeId: order.ptid||ress[5].data.data[0].id,
        carPrice: order.car_price||'',
        seatsList: ress[6].data.data,
        selectedSeats: order.sname||ress[6].data.data[0].option,
        selectedSeatsId: order.sid||ress[6].data.data[0].id,
        engineNumber: order.engine_number||'',
        carColor: order.car_color||'',
        purchaseDate: order.purchase_date||"",
        memo: order.memo||'',
        paymentList: ress[7].data.data,
        selectedPayment: order.pmname||ress[7].data.data[0].option,
        selectedPaymentId: order.pmid||ress[7].data.data[0].id,
        paymentSerial: order.payment_serial||'',
        paymentEvidence: order.payment_evidence||'',
        payment_timestamp: order.payment_timestamp||'',
        selectedCarId: order.brand_car_series||ress[8].data.data[0].id,
        selectedServices: order.order_services.map(s=>{
          s.discount_price=parseFloat(s.discount_price)
          s.start_date=formattedGMTDate(s.start_date).split(' ')[0];
          s.end_date=formattedGMTDate(s.end_date).split(' ')[0];
          return s
        })||[],
        totalPrice: order.order_services?order.order_services.filter(s=>!s.is_gift).reduce((acc, cur) => acc + cur.discount_price, 0).toFixed(2):0,
        has_modification: order.has_modification||0,
        invoiceImagePath: order.invoice_image||'',
        modificationImagePath: order.modification_image||'',
        created_at: order.created_at?formattedGMTDate(order.created_at):''
      })
      this.initCarsData(ress[8].data.data);
      const res = await serviceService.listByCarId(this.data.selectedCarId)
      this.initServices(res.data.data);
      //隐藏加载动画并允许页面操作
      wx.hideLoading();
    },
    async saveOrder(e) {
      const to_pay=e.currentTarget.dataset.to_pay;
      const { name, phone, selectedIdType, idNumber, carPrice } = this.data;
      //如果姓名、电话、证件号码、车辆发票价为空，提示用户填写对应信息
      if (name == '' || phone == '' || idNumber == '' || carPrice == '') {
        wx.showModal({
          title: '客户或车辆信息不完整',
          content: '请填写姓名、电话、证件号码、车辆发票价',
          showCancel: false,
          confirmText: '知道了'
        });
        return;
      }
      //验证手机号格式是否正确
      if (!/^1[3456789]\d{9}$/.test(phone)) {
        wx.showToast({
          title: '手机号格式错误',
          icon: 'error',
          duration: 2000
        });
        return;
      }
      //如果证件类型是身份证，验证身份证号码格式是否正确
      if (selectedIdType == '身份证') {
        if (!/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idNumber)) {
          wx.showToast({
            title: '身份证格式错误',
            icon: 'error',
            duration: 2000
          })
          return;
        }
      }
      //验证carPrice必须是数字
      if (!/^[0-9]+$/.test(carPrice)) {
        wx.showToast({
          title: '发票价必须数字',
          icon: 'error',
          duration: 2000
        });
        return
      }

      const {
        has_modification,
        invoiceImagePath,
        modificationImagePath,
      } = this.data;
      //如果有改装件，则必须提供发票图片和改装件图片
      if (has_modification == 1) {
        if (invoiceImagePath == '' || modificationImagePath == '') {
          wx.showModal({
            title: '改装件信息不完整',
            content: '请上传发票图片和改装件图片',
            showCancel: false,
            confirmText: '知道了'
          });
          return;
        }
      }
      const {
        selectedServices
      } = this.data;
      //如果serviceList为空，提示用户选择服务
      if (selectedServices.length == 0) {
        wx.showToast({
          title: '请选择产品购买',
          icon: 'error',
          duration: 2000
        });
        return;
      }
      if(!to_pay){
        const app=getApp()
        await app.globalData.recorderManager.stop();
      }
      //先弹出等待框
      wx.showLoading({
        title: '提交中...',
        mask: true,
      })
      if(has_modification==1){
        var invoiceImageBase64 = invoiceImagePath.startsWith('http') ? "data:image/png;base64," + wx.getFileSystemManager().readFileSync(invoiceImagePath, 'base64') : invoiceImagePath;
        //将this.data.modificationImagePath文件转为base64格式
        var modificationImageBase64 = modificationImagePath.startsWith('http') ? "data:image/png;base64," + wx.getFileSystemManager().readFileSync(modificationImagePath, 'base64') : modificationImagePath;
      }
      const { selectedReferrerId, selectedCustomerTypeId, selectedCustomerSrcId, selectedIdTypeId, selectedPurchaseTypeId,
        address, vin, selectedSeatsId, engineNumber, carColor, purchaseDate, selectedCarId, store, memo
      } = this.data;
      console.log(selectedServices);
      orderService.update({
        id:this.data.order.id,
        referrer_id: selectedReferrerId,
        customer_id:this.data.order.customer_id,
        customer_type: selectedCustomerTypeId,
        name: name,
        phone: phone,
        customer_source: selectedCustomerSrcId,
        id_type: selectedIdTypeId,
        id_number: idNumber,
        address,
        vin,
        purchase_type: selectedPurchaseTypeId,
        car_price: carPrice,
        seats: selectedSeatsId,
        engine_number: engineNumber,
        car_color: carColor,
        purchase_date: purchaseDate,
        brand_car_series: selectedCarId,
        order_services: JSON.stringify(selectedServices),
        has_modification,
        invoice_image: invoiceImageBase64,
        modification_image: modificationImageBase64,
        store_id: this.data.store_id,
        payment_method: this.data.selectedPaymentId,
        memo
      }).then(res => {
        wx.hideLoading()
        wx.showToast({
          title: '提交成功',
          icon: 'success',
          duration: 1000,
          success: () => {
            setTimeout(() => {
              if(to_pay){
                //跳转到order/pay/pay页面
                wx.navigateTo({
                  url: '/pages/order/pay/pay?id=' + res.data.order.id+"&"+"payment="+this.data.selectedPayment+"&"+"payment_id="+this.data.selectedPaymentId+"&"+"total="+parseFloat(this.data.totalPrice)
                })
              }else{
                wx.switchTab({
                  url: '/pages/order/list/list', 
                })
              }
            }, 1000);
          }
        });
      })
    },
    async failOrder(){
      //检查memo是否为空
      if(this.data.memoplus==''){
        wx.showToast({
          title: '请填写战败备注',
          icon: 'error',
          duration: 2000
        }) 
        return
      }
      //显示加载动画并禁止页面操作
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      await orderService.status({
        id:this.data.order.id,
        order_status:2,
        memo:this.data.memo+" 战败备注："+this.data.memoplus
      })
      wx.hideLoading()
      const app=getApp()
      await app.globalData.recorderManager.stop();
      //返回订单列表页
      wx.switchTab({
        url: '/pages/order/list/list', 
      })
    },
    bindIdInput(e) {
      this.setData({ idNumber: e.detail.value });
    },
    bindAddrInput(e) {
      this.setData({ address: e.detail.value });
    },
    bindMemoInput(e) {
      this.setData({ memo: e.detail.value });
    },
    bindPaymentInput(e) {
      this.setData({ payment_number: e.detail.value });
    },
    handlePaymentSelect(e) {
      if(this.data.order.order_status>0)
        return
      const id = e.currentTarget.dataset.id
      const option = e.currentTarget.dataset.option
      this.setData({
        selectedPayment: option,
        selectedPaymentId: id
      })
    },
    handleMemoInput(e) {
      this.setData({ memo: e.detail.value })
    },
    handleModificationRadioChange(e) {
      if(this.data.order.order_status>0)
        return
      this.setData({ has_modification: e.detail.value });
    },
    // 新增图片处理方法
    chooseImage(e) {
      const { fieldname, tempFilePath } = e.detail;
      this.setData({ [fieldname]: tempFilePath })
    },
    removeImage(e) {
      const { fieldname } = e.detail;
      this.setData({ [fieldname]: '' })
    },
    bindStartDateChange(e) {
      const { index, item } = e.detail;
      const selectedServices = this.data.selectedServices;
      selectedServices[index] = item;
      this.setData({ selectedServices });
    },
    removeService(e) {
      const { csa_id } = e.detail;
      const servicesId = this.data.selectedServicesId.filter(it => it != csa_id);
      const services = this.data.selectedServices.filter(item => item.csa_id !== csa_id);
      const totalPrice = services.reduce((box, item) => {
        return box + item.discount_price;
      }, 0)
      //修改二维数组中id为id的元素的checked属性为false，并返回修改后的完整二维数组
      const serviceList = this.data.serviceList.map(
        services => services.map(
          service => {
            service.checked = servicesId.includes(service.csa_id)
            return service
          }
        ) 
      )
      this.setData({ selectedServices: services, selectedServicesId: servicesId, totalPrice, serviceList  });
    },
    onRadioChange(e) {
      const { csa_id, outerIndex } = e.detail;
      var services = this.data.serviceList[outerIndex];
      if (this.data.selectedServicesId.includes(csa_id)) {
        var newSelected =
          this.data.selectedServicesId.filter(it => it != csa_id)
      } else {
        var oldSelected =
          this.data.selectedServicesId.filter(
            it => services.some(s => s.csa_id == it) == false
          )
        var newSelected = [...oldSelected, csa_id];
      }
      services = services.map(
        service => {
          service.checked = newSelected.includes(service.csa_id)
          return service
        }
      )
      newSelected.sort((a, b) => a - b)
      const serviceList = this.data.serviceList;
      serviceList[outerIndex] = services;
      this.setData({
        selectedServicesId: newSelected,
        serviceList
      });
    },
    // 显示选择器
    showPicker() {
      if(this.data.order.order_status>0)
        return
      this.setData({ showCustomPicker: true });
    },

    // 隐藏选择器
    hidePicker() {
      this.setData({ showCustomPicker: false });
    },

    // 确认选择
    confirmPicker() {
      const selectedServices = this.data.selectedServices;
      selectedServices.length = 0;
      var totalPrice = 0;
      //遍历serviceList二维数组
      for (var services of this.data.serviceList) {
        for (var service of services) {
          if (this.data.selectedServicesId.includes(service.csa_id)) {
            selectedServices.push(service)
            totalPrice += service.discount_price
          }
        }
      }
      this.setData({
        selectedServices,
        showCustomPicker: false,
        totalPrice
      })
    },

    // 滚动选择事件
    bindPickerViewChange(e) {
      this.setData({
        pickerValue: e.detail.value
      });
    },

    // 初始化地址数据
    initCarsData(data) {
      const rawData = data;
      const selectedCarId = this.data.selectedCarId;
      const selectedCar = rawData.filter(item => item.id == selectedCarId)[0];
      
      const carsMap = new Map();

      // 处理原始数据
      rawData.forEach(item => {
        // 省份处理
        if (!carsMap.has(item.brand)) {
          carsMap.set(item.brand, {
            name: item.brand,
            models: new Map()
          });
        }
        const car = carsMap.get(item.brand);

        // 城市处理
        if (!car.models.has(item.model)) {
          car.models.set(item.model, {
            name: item.model,
            styles: []
          });
        }
        const model = car.models.get(item.model);

        // 区县处理
        model.styles.push({
          id: item.id,
          name: item.style
        });
      });

      const brandIndex=Array.from(carsMap.keys()).indexOf(selectedCar.brand);
      const modelIndex=Array.from(
        Array.from(carsMap.values())[brandIndex].models.keys()
      ).indexOf(selectedCar.model);
      const styleIndex= Array.from(
        Array.from(carsMap.values())[brandIndex].models.values()
      )[modelIndex].styles.map(c => c.name).indexOf(selectedCar.style);

      // 新增名称数组处理
      this.setData({
        carList:data,
        carsMap,
        multiIndex: [
           brandIndex,
           modelIndex,
           styleIndex
        ],
        brands: Array.from(carsMap.keys()),
        models: Array.from(
          Array.from(carsMap.values())[brandIndex].models.keys()
        ),
        styles: Array.from(
          Array.from(carsMap.values())[brandIndex].models.values()
        )[modelIndex].styles.map(c => c.name)
      });
    },

    // 处理picker列变化
    bindMultiPickerColumnChange(value, column) {

      const { carsMap, multiIndex } = this.data;
      let newIndex = [...multiIndex];
      newIndex[column] = value;
      if (column === 0) { // 省份变化
        const newModels =
          Array.from(carsMap.values())[value].models;
        this.setData({
          models: Array.from(newModels.keys()),
          styles: Array.from(newModels.values())[0].styles.map(c => c.name),
          multiIndex: [value, 0, 0]
        });
      } else if (column === 1) { // 城市变化
        const model = Array.from(
          Array.from(carsMap.values())[multiIndex[0]].models.values()
        )[value];
        const newStyles = model.styles.map(c => c.name);
        this.setData({
          styles: newStyles,
          multiIndex: [multiIndex[0], value, 0]
        });
      } else {
        // 更新对应名称数组
        this.setData({
          multiIndex: [multiIndex[0], multiIndex[1], value]
        });
      }
    },

    // 确认选择
    bindMultiPickerChange(e) {
      const value = e.detail.value;
      const column = parseInt(e.currentTarget.dataset.col);
      this.bindMultiPickerColumnChange(value, column);
      const { brands, models, styles, multiIndex, carList } = this.data;
      const selectedCarId = carList.filter(
        item =>
          item.brand == brands[multiIndex[0]] &&
          item.model == models[multiIndex[1]] &&
          item.style == styles[multiIndex[2]]
      )[0].id;
      serviceService.listByCarId(selectedCarId).then(
        res => {
          this.setData({
            selectedServices: [],
            totalPrice:0,
            selectedServicesId: []
          })
          this.initServices(res.data.data) 
        }
      )
    },
    initServices(data) {
      //将res.data.data数组，按每个元素对象的category_name值不同，分成多个自数组
      const groupedData = data.reduce((acc, cur) => {
        const key = cur.category_name;
        if (!acc[key]) {
          acc[key] = [];
        }
        cur.checked = this.data.selectedServices.some(s=>s.csa_id==cur.csa_id);
        cur.start_date = cur.start_date = new Date(new Date().setHours(0, 0, 0, 0)).toISOString().split('T')[0];
        //获得开始日期中的年份
        const startDate = new Date(cur.start_date);
        const year = new Date(cur.start_date).getFullYear() + cur.service_years;
        startDate.setFullYear(startDate.getFullYear() + cur.service_years);
        startDate.setDate(startDate.getDate() - 1);
        cur.end_date = startDate.toISOString().split('T')[0];
        cur.is_gift=0;
        acc[key].push(cur);
        return acc;
      }, {});
      this.setData({
        selectedServicesId: this.data.selectedServices.map(s=>s.csa_id),
        serviceMap: groupedData,
        serviceList: Object.values(groupedData),
        categoryNames: Object.keys(groupedData)
      })
    },
    bindPickerChange(e) {
      const index = e.detail.value;
      const selected = this.data.referrerList[index];
      this.setData({
        selectedReferrer: selected.username,
        selectedReferrerId: selected.id
      });
    },
    // 类型选择处理
    handleTypeSelect(e) {
      if(this.data.order.order_status>0)
        return
      const typeId = e.currentTarget.dataset.id
      const typeName = e.currentTarget.dataset.option
      this.setData({
        selectedCustomerType: typeName,
        selectedCustomerTypeId: typeId
      })
    },
    handleSrcTypeSelect(e) {
      if(this.data.order.order_status>0)
        return
      const typeId = e.currentTarget.dataset.id
      const typeName = e.currentTarget.dataset.option
      this.setData({
        selectedCustomerSrc: typeName,
        selectedCustomerSrcId: typeId
      })
    },
    handleIdTypeSelect(e) {
      if(this.data.order.order_status>0)
        return
      const typeId = e.currentTarget.dataset.id
      const typeName = e.currentTarget.dataset.option
      this.setData({
        selectedIdType: typeName,
        selectedIdTypeId: typeId
      })
    },
    handlePurchaseTypeSelect(e) {
      if(this.data.order.order_status>0)
        return
      const typeId = e.currentTarget.dataset.id
      const typeName = e.currentTarget.dataset.option
      this.setData({
        selectedPurchaseType: typeName,
        selectedPurchaseTypeId: typeId
      })
    },
    handleSeatsSelect(e) {
      if(this.data.order.order_status>0)
        return
      const typeId = e.currentTarget.dataset.id
      const typeName = e.currentTarget.dataset.option
      this.setData({
        selectedSeats: typeName,
        selectedSeatsId: typeId
      })
    },
    bindPurchaseDateChange(e) {
      this.setData({
        purchaseDate: e.detail.value
      });
    },
    bindEngineNumberInput(e) {
      // 过滤非数字字符
      const value = e.detail.value;
      this.setData({
        engineNumber: value
      });
    },
    bindCarColorInput(e) {
      // 过滤非数字字符
      const value = e.detail.value
      this.setData({
        carColor: value
      });
    },
    bindNameInput(e) {
      // 过滤非数字字符
      const value = e.detail.value;
      this.setData({
        name: value
      });
    },
    bindIdNumberInput(e) {
      // 过滤非数字字符
      const value = e.detail.value;
      this.setData({
        idNumber: value
      });
    },
    bindAddressInput(e) {
      // 过滤非数字字符
      const value = e.detail.value;
      this.setData({
        address: value
      });
    },
    bindVinInput(e) {
      // 过滤非数字字符
      const value = e.detail.value;
      this.setData({
        vin: value
      })
    },
    bindCarPriceInput(e) {
      // 过滤非数字字符
      const value = e.detail.value;
      this.setData({
        carPrice: value
      })
    },
    bindPhoneInput(e) {
      // 过滤非数字字符
      const value = e.detail.value.replace(/\D/g, '');
      this.setData({
        phone: value
      });
    },
    validatePhone(e) {
      const value = this.data.phone;
      const isValid = /^1[3-9]\d{9}$/.test(value);

      this.setData({
        isPhoneValid: isValid
      });

      if (!isValid && value) {
        wx.showToast({
          title: '手机号格式错误',
          icon: 'none'
        });
      }
    },
    validateId(e) {
      const { selectedIdType, idNumber } = this.data;
      //如果证件类型是身份证，验证身份证号码格式是否正确
      if (selectedIdType == '身份证') {
        if (!/^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(idNumber)) {
          wx.showToast({
            title: '身份证格式错误',
            icon: 'error',
            duration: 2000
          })
        }
      }
    }
  },
  // 组件生命周期（替代Page的onLoad）
  lifetimes: {
    attached() { // 对应页面的onLoad
      // 这里写原本在page onLoad中的初始化逻辑
      // console.log('组件被插入页面节点树时触发')
      console.log("order-detail.js 的lifetimes的attached()")
      this.onLoad()
    },
    detached() { // 对应页面的onUnload
      // 组件卸载逻辑
    }
  },

  // 如果还需要使用页面生命周期（比如所在页面的onShow）
  pageLifetimes: {
    show() { // 对应页面的onShow
      // 页面显示时的逻辑
      
    },
    hide() { // 对应页面的onHide
      // 页面隐藏时的逻辑  
    }
  }
})